<template>
  <el-dialog
    v-model="dialogVisible"
    title="订单确认"
    width="500px"
    @close="onClose"
    align-center
  >
    <div v-if="product" class="order-summary">
      <div class="product-info-line">
        <el-image :src="product.imageUrl" class="product-image" fit="cover" />
        <div class="product-details">
          <span class="product-name">{{ product.name }}</span>
          <span class="quantity">x {{ quantity }}</span>
        </div>
        <span class="price-value">¥{{ (product.price * quantity).toFixed(2) }}</span>
      </div>
      
      <el-divider />
      
      <div class="cost-details">
        <div class="cost-line">
          <span>商品小计</span>
          <span>¥{{ subtotal.toFixed(2) }}</span>
        </div>
        <div class="cost-line">
          <span>运费</span>
          <span>¥{{ shippingFee.toFixed(2) }}</span>
        </div>
        <div class="cost-line">
          <span>折扣</span>
          <span>- ¥{{ discount.toFixed(2) }}</span>
        </div>
      </div>

      <el-divider />

      <div class="total-amount">
        <span>总计</span>
        <span class="total-price">¥{{ total.toFixed(2) }}</span>
      </div>
    </div>
    
    <div v-if="addresses.length" class="address-section">
      <div class="address-header">
        <span>收货地址</span>
        <el-button type="primary" link @click="openAddressDialog">新增地址</el-button>
      </div>
      <el-radio-group v-model="selectedAddressId">
        <el-radio
          v-for="addr in addresses"
          :key="addr.id"
          :label="addr.id"
          class="address-radio"
        >
          {{ addr.country }} {{ addr.province }} {{ addr.city }} {{ addr.county }} {{ addr.detailAddress }} - {{ addr.receiverName }} {{ addr.receiverPhone }}
        </el-radio>
      </el-radio-group>
    </div>
    <el-empty v-else description="暂无地址，请新增地址" />

    <el-dialog v-model="addressDialogVisible" title="新增地址" width="500px" @close="resetAddressForm">
      <el-form :model="formAddress" label-width="100px" ref="addressFormRef" :rules="addressRules">
        <el-form-item label="收件人" prop="receiverName"><el-input v-model="formAddress.receiverName" /></el-form-item>
        <el-form-item label="联系电话" prop="receiverPhone"><el-input v-model="formAddress.receiverPhone" /></el-form-item>
        <el-form-item label="国家" prop="country"><el-input v-model="formAddress.country" /></el-form-item>
        <el-form-item label="省份" prop="province"><el-input v-model="formAddress.province" /></el-form-item>
        <el-form-item label="城市" prop="city"><el-input v-model="formAddress.city" /></el-form-item>
        <el-form-item label="地区/县" prop="county"><el-input v-model="formAddress.county" /></el-form-item>
        <el-form-item label="详细地址" prop="detailAddress"><el-input v-model="formAddress.detailAddress" type="textarea" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addressDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="submitAddressForm">保存</el-button>
      </template>
    </el-dialog>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onClose">取消</el-button>
        <el-button type="primary" @click="handleConfirmOrder" :loading="isSubmitting">
          确认下单
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, toRefs, watch, reactive } from 'vue';
import apiClient from '../axios/axios';
import { ElMessage } from 'element-plus';
import { useUserStore } from '../stores/user';

interface Product {
  id: number;
  name: string;
  price: number;
  imageUrl: string;
}

interface Address {
  id: number;
  receiverName: string;
  receiverPhone: string;
  country: string;
  province: string;
  city: string;
  county: string;
  detailAddress: string;
}

const props = defineProps<{
  visible: boolean;
  product: Product | null;
  quantity: number;
}>();

const emit = defineEmits(['update:visible', 'order-success']);

const userStore = useUserStore();
const { visible, product, quantity } = toRefs(props);
const isSubmitting = ref(false);

const dialogVisible = computed({
  get: () => visible.value,
  set: (value) => emit('update:visible', value),
});

// --- Calculation ---
const shippingFee = ref(10.00); // Example shipping fee
const discount = ref(5.00);    // Example discount

const subtotal = computed(() => {
  if (!product.value) return 0;
  return product.value.price * quantity.value;
});

const total = computed(() => {
  return subtotal.value + shippingFee.value - discount.value;
});

// --- address ---
const addresses = ref<Address[]>([]);
const selectedAddressId = ref<number | null>(null);

const loadAddresses = async () => {
  const user = userStore.user;
  if (!user) return;
  try {
    const res = await apiClient.get<Address[]>(`/address/user/${user.id}`);
    addresses.value = res.data;
    if (!selectedAddressId.value && addresses.value.length) {
      selectedAddressId.value = addresses.value[0].id;
    }
  } catch (e) {
    console.error('加载地址失败', e);
  }
};

watch(dialogVisible, (val) => {
  if (val) {
    loadAddresses();
  }
});

// --- address dialog ---
const addressDialogVisible = ref(false);
const addressFormRef = ref<any>();

const initialForm: Omit<Address, 'id'> = {
  receiverName: '',
  receiverPhone: '',
  country: '中国',
  province: '',
  city: '',
  county: '',
  detailAddress: '',
};
const formAddress = reactive({ ...initialForm });

const addressRules = {
  receiverName: [{ required: true, message: '请输入收件人', trigger: 'blur' }],
  receiverPhone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  country: [{ required: true, message: '请输入国家', trigger: 'blur' }],
  province: [{ required: true, message: '请输入省份', trigger: 'blur' }],
  city: [{ required: true, message: '请输入城市', trigger: 'blur' }],
  county: [{ required: true, message: '请输入地区/县', trigger: 'blur' }],
  detailAddress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
};

const resetAddressForm = () => {
  Object.assign(formAddress, initialForm);
  addressFormRef.value?.clearValidate();
};

const openAddressDialog = () => {
  resetAddressForm();
  addressDialogVisible.value = true;
};

const submitAddressForm = async () => {
  if (!addressFormRef.value) return;
  await addressFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return;
    const user = userStore.user;
    if (!user) return;
    try {
      const payload = { ...formAddress, userId: user.id };
      const res = await apiClient.post('/address', payload);
      ElMessage.success('地址已保存');
      addressDialogVisible.value = false;
      await loadAddresses();
      selectedAddressId.value = res.data.id;
    } catch (e) {
      ElMessage.error('保存地址失败');
    }
  });
};

// --- Actions ---
const onClose = () => {
  dialogVisible.value = false;
};

const handleConfirmOrder = async () => {
  if (!product.value) return;

  const user = userStore.user;
  if (!user) {
    ElMessage.error('用户未登录，无法下单。');
    return;
  }
 
  if (!selectedAddressId.value) {
    ElMessage.warning('请选择收货地址');
    return;
  }

  isSubmitting.value = true;
  
  try {
    const orderPromises = [];
    for (let i = 0; i < quantity.value; i++) {
      const isFirstOrder = i === 0;
      const orderPayload = {
        customerId: user.id,
        productId: product.value.id,
        addressId: selectedAddressId.value,
        subtotalAmount: product.value.price,
        shippingFee: isFirstOrder ? shippingFee.value : 0,
        discountAmount: isFirstOrder ? discount.value : 0,
        totalAmount: product.value.price + (isFirstOrder ? shippingFee.value : 0) - (isFirstOrder ? discount.value : 0)
      };
      orderPromises.push(apiClient.post('/orders', orderPayload));
    }
    
    await Promise.all(orderPromises);
    
    ElMessage.success(`成功创建 ${quantity.value} 个订单！`);
    emit('order-success');
    onClose();
  } catch (error) {
    console.error('创建订单失败:', error);
    ElMessage.error('创建订单失败，请稍后重试。');
  } finally {
    isSubmitting.value = false;
  }
};
</script>

<style scoped>
.order-summary {
  font-size: 14px;
}
.product-info-line {
  display: flex;
  align-items: center;
  gap: 15px;
}
.product-image {
  width: 60px;
  height: 60px;
  border-radius: 4px;
}
.product-details {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
}
.product-name {
  font-weight: 500;
}
.quantity {
  color: #909399;
  font-size: 12px;
}
.price-value {
  font-weight: 500;
}

.cost-details {
  display: flex;
  flex-direction: column;
  gap: 10px;
  color: #606266;
}
.cost-line {
  display: flex;
  justify-content: space-between;
}

.total-amount {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: bold;
}
.total-price {
  font-size: 20px;
  color: #F56C6C;
}

.address-section{margin-top:16px}
.address-header{display:flex;justify-content:space-between;align-items:center;margin-bottom:8px}
.address-radio{display:block;margin-bottom:6px}
</style> 